<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link href="https://cdn.bootcdn.net/ajax/libs/nprogress/0.2.0/nprogress.css" rel="stylesheet">
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script src="https://cdn.bootcdn.net/ajax/libs/nprogress/0.2.0/nprogress.js"></script>
</head>

<body>
  <h1>拦截器练习</h1>
  <input type="text" id="ipt">
  <button id="btn">点击获取数据</button>
  <script>
    // 创建axios实例
    const myAxios = axios.create({
      baseURL: '/',
      timeout: 10000,
      header: {}
    })

    // 设置请求拦截器
    myAxios.interceptors.request.use((config) => {
      NProgress.start()

      // 让请求头携带token
      const token = 'dfsgnjosdnfoskgsgol'
      config.header.token = token
      return config
    }, (err) => {
      return Promise.reject(err.message)
    })

    // 设置响应拦截器
    myAxios.interceptors.response.use((res) => {
      NProgress.done()

      // 对响应的数据进行处理,成功的直接返回,错误的直接交给异常处理
      if (res.data.code !== 10000) {
        return Promise.reject(res.data.msg)
      }
      return res.data.data
    }, (err) => {
      return Promise.reject(err.message)
    })

    // 获取元素
    const oipt = document.getElementById('ipt')
    const obtn = document.getElementById('btn')

    // 绑定点击事件
    obtn.onclick = async function () {
      // 获取文本框的内容
      const iptValue = oipt.value

      try {
        const re = await myAxios.get('/user',{
          params : {
            userId : iptValue
          }
        })
        console.log(re);
      }catch(e){
        console.log(e);
      }
    }
  </script>
</body>

</html>